<template>
    <div class="">
        <div class="e-m-t-45 e-m-b-45" v-if="parentId == 0">
            <el-radio-group v-model="dataType">
                <el-radio-button label="0">客户组列表</el-radio-button>
                <el-radio-button label="1">部门列表</el-radio-button>
            </el-radio-group>
        </div>
        <div class="e-m-t-30">
            <div class="flex">
                <div class="e-flex-1">
                    <el-button type="primary" icon="el-icon-plus" plain @click="dialogVisible = true">新建</el-button>
                    <!-- <el-button type="primary" @click="down()" plain><i class="iconfont icon-excel e-m-r-5"></i>导入Excel</el-button> -->
                </div>

                <el-form :inline="true" class="demo-form-inline">
                    <!-- <el-form-item label="所属地区">
                        <cityList v-model="cityId" @change="SelectSearchCity"></cityList>
                    </el-form-item> -->
                    <el-form-item label="客户组名称">
                        <el-input placeholder="请输入" v-model="namekey" prefix-icon="el-icon-search" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getList(typeId)">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 更多筛选条件 -->
        <div class="other-search-form" :class="isActive ? 'is-active' : ''" v-if="parentId == 0">
            <el-form label-position="left" :inline="true" size="small">
                <div class="flex align-items-center">
                    <!-- 时间筛选 -->
                    <timeChangeList v-model="timeType" @input="getList(typeId, true)" @change="changeTime"></timeChangeList>
                </div>
                <div class="flex align-items-center">
                    <div class="e-flex-1">
                        <el-form-item label="所属地区">
                            <cityList v-model="cityId" @change="SelectCityList"></cityList>
                        </el-form-item>
                    </div>
                    <div class="e-flex-1">
                        <el-form-item label="所属加盟商" v-if="franchiseId == null">
                            <franchiseList v-model="listFranchiseId" @change="selectFranchise"></franchiseList>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>
        <div class="type-state e-m-b-30 e-m-t-30" v-if="parentId == 0">
            <span :class="{ 'on': typeId == null }" @click="getList(null, true)">全部</span>
            <span v-for="(item, index) in typeArr" :key="index" :class="{ 'on': typeId == item.value }"
                @click="getList(item.value, true)">{{ item.name }}</span>
        </div>

        <el-table :data="tableData" style="width: 100%" :border="true" stripe @row-click="rowClick">
            <el-table-column fixed type="index" width="50">
            </el-table-column>
            <el-table-column prop="name" label="客户组名称" v-if="parentId == 0">
                <template slot-scope="scope">
                    <el-tag size="mini">{{ scope.row.type }}</el-tag>
                    <span>{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="department" label="部门名称" v-if="parentId > 0">
                <template slot-scope="scope">
                    <span>{{ scope.row.department }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="user" label="绑定账号">
                <template slot-scope="scope">
                    <span v-if="scope.row.user"><el-button type="text" @click="userViews(scope.row.user)">{{ scope.row.user.name || '--' }}{{ scope.row.parentid == 0?'(管理员)':'' }}({{ scope.row.user.mobile }})</el-button></span>
                    <span v-else>未绑定</span>
                </template>
            </el-table-column>
            <el-table-column prop="franchise" label="所属加盟商" width="200">
                <template slot-scope="scope">
                    <span>{{ scope.row.franchise.name || '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="citynames" label="所属地区" width="200">
                <template slot-scope="scope">
                    <span>{{ scope.row.citynames || '--' }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="departmentcount" label="部门数" width="150">
            </el-table-column> -->
            <!-- <el-table-column prop="type" label="客户组类型" width="150">
            </el-table-column> -->
            <el-table-column prop="regdate" label="注册时间" width="150">
            </el-table-column>
            <el-table-column prop="lastlogindatetime" label="最后登录时间" width="150">
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="按住ctrl键+鼠标左键新窗口打开" placement="left-start">
                        <el-button type="text" size="small" @click.stop="views($event, scope.row)">查看</el-button>
                    </el-tooltip>
                    <!-- <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button> -->
                    <!-- <el-button type="text" size="small" @click="goGuest(scope.row.id)">查看推广客户</el-button>
                    <el-button type="text" size="small" @click="goRecord(scope.row.id)">查看推广佣金</el-button> -->
                    <!-- <el-button type="text" size="small">重置密码</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <div class="table-pagination">
            <el-pagination background layout="sizes, total, prev, pager, next" :total="total"
                :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" :current-page="page" @current-change="pageChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </div>
        <el-dialog :title="parentId > 0?'新建部门':'新建客户组'" :visible.sync="dialogVisible" width="500px" :append-to-body="true">
            <el-form ref="addForm" :model="addForm" :rules="rules" label-width="100px">
                <el-form-item :label="parentId > 0?'部门名称':'客户组名称'" prop="enterprisename">
                    <el-input v-model="addForm.enterprisename"></el-input>
                </el-form-item>
                <el-form-item label="所属加盟商" prop="franchiseId" v-if="parentId == 0">
                    <franchiseList v-model="addForm.franchiseId"></franchiseList>
                </el-form-item>
                <el-form-item label="客户组类型" prop="enterprisetype" v-if="parentId == 0">
                    <el-select v-model="addForm.enterprisetype" placeholder="请选择客户组类型">
                        <el-option v-for="item in typeArr" :key="item.value" :label="item.name" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所在地区" v-if="dialogVisible" prop="cityid">
                    <cityList v-model="addForm.cityId" style="width: 100%;margin-right: 20px"></cityList>
                </el-form-item>
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
                <!-- <el-form-item label="初始密码">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item> -->
            </el-form>
            <el-divider v-if="parentId == 0"></el-divider>
            <el-form label-width="100px" label-position="top" v-if="parentId == 0">
                <el-form-item label="客户组账户管理模式：">
                    <el-radio-group v-model="addForm.type">
                        <div class="e-p-b-15">
                            <el-radio label="0">余额账户分管</el-radio>
                            <div class="tips e-font-14 e-p-l-24">账户分管模式为，各部门回收余额分给各部门管理</div>
                        </div>
                        <div>
                            <el-radio label="1">余额账户统管</el-radio>
                            <div class="tips e-font-14 e-p-l-24">账户统管模式为，各部门回收余额统一到客户组内，授权给一个部门进行管理（新建客户组为首个部门，创建后可更换）</div>
                        </div>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createUser" :loading="loading">确定</el-button>
            </span>
        </el-dialog>
        <!-- 详情页面弹窗 -->
        <el-drawer title="" :visible.sync="viewShow.show" direction="rtl" size="80%" :with-header="false" :append-to-body="true">
            <enterpriseView v-if="viewShow.show" :id="viewShow.id" @goBack="viewShow.show = false"></enterpriseView>
        </el-drawer>
        <!-- 用户详情页面弹窗 -->
        <el-drawer title="" :visible.sync="userView.show" direction="rtl" size="80%" :with-header="false" :append-to-body="true">
            <userView v-if="userView.show" :id="userView.id" @goBack="userView.show = false"></userView>
        </el-drawer>
    </div>
</template>

<script>
import timeChangeList from '@/components/form-select-type/timeChangeList.vue'
import franchiseList from '@/components/form-select-type/franchiseList.vue'
import cityList from '@/components/form-select-type/cityList.vue'
import enterpriseView from './views'
import userView from '@/pages/user/components/views.vue'
export default {
    name: "enterpriseList",
    components: {
        enterpriseView,
        franchiseList,
        cityList,
        timeChangeList,
        userView
    },
    props: {
        franchiseId: {
            type: [Number, String],
            default: null
        },
        parentId:{
            type: [Number, String],
            default: 0
        }
    },
    data() {
        return {
            // 时间类型
            timeType: 0, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
            startDate: '', //开始时间
            endDate: '', //结束时间
            isActive: true,
            listFranchiseId: null,
            viewShow: {
                id: 0,
                show: false //详情页面弹窗
            },
            form: {
                EnterpriseName: '',
                IsSchool: false,
                Path: ''
            },
            userView: {
                id: 0,
                show: false
            },
            dialogVisible2: false,//导出弹窗
            fileList: [],
            usertype: 0,
            loading: true,
            namekey: '',
            phonekey: '',
            page: 1,
            pageSize: 10,
            total: 0,
            tableData: [],
            // 新增客户组
            dialogVisible: false,
            addForm: {
                franchiseId: null,
                userId: 0,
                name: '',
                type: "0",
                enterpriseType: 0,
                cityName: '',
                cityPath: '',
                cityid: 0,
                mobile: null
            },
            rules: {
                enterprisename: [
                    { required: true, message: '请填写客户组名', trigger: 'blur' },
                ],
                franchiseId: [
                    { required: true, message: '请选择加盟商', trigger: 'change' },
                ],
                department: [
                    { required: true, message: '请填写部门名', trigger: 'blur' },
                ],
                enterprisetype: [
                    { required: true, message: '请选择客户组类型', trigger: 'change' },
                ],
                cityId: [
                    { required: true, message: '请选择地区', trigger: 'change' },
                ],
                // mobile: [
                //     { required: true, message: '请填写手机号', trigger: 'blur' },
                // ],
                // name: [
                //     { required: true, message: '请填写用户名', trigger: 'blur' },
                // ]
            },
            addFormInputState: false,
            dataType: 0,
            typeArr: [
                // {
                // 	name: '全部',
                // 	value: null
                // },
                {
                    name: '企业',
                    value: 1
                },
                {
                    name: '学校',
                    value: 2
                },
                {
                    name: '机关',
                    value: 3
                },
                {
                    name: '环卫',
                    value: 4
                }
            ],
            typeId: 0,
            cityId: 0
        }
    },
    mounted() {
        this.getList()
    },
    computed: {
        headers() {
            return this.$store.state.header
        }
    },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.addForm = {
                    franchiseId: null,
                    userId: 0,
                    name: '',
                    type: "0",
                    enterpriseType: 0,
                    cityName: '',
                    cityPath: '',
                    cityid: 0
                }
            }
        },
        dataType(val) {
            console.log(val)
            if (val == 0) {
                this.$router.push({
                    path: '/enterprise/list'
                })
            } else if (val == 1) {
                this.$router.push({
                    path: '/enterprise/department/list'
                })
            }
        }
    },
    methods: {
        // 查看用户详情
        userViews(item){
            this.userView.id = item.id
            this.userView.show = true
        },
        createUser() { //新增客户组
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    let param = {
                        enterpriseId: 0, //0为创建客户组， 非0为创建部门（部门的上级客户组ID）
                        // franchiseId: this.addForm.franchiseId,
                        name: this.addForm.enterprisename,
                        cityId: this.addForm.cityId,
                        type: this.addForm.enterprisetype,
                        // mode: this.addForm.type,
                        user: {
                            defaultPassType: 0, //密码为空时生效 0.888888 1.随机 其它.手机后几位
                            name: this.addForm.name,
                            mobile: this.addForm.mobile,
                            password: this.addForm.password
                        }
                    }
                    // 新建部门时的参数改变
                    if (this.parentId) {
                        param.enterpriseId = this.parentId
                    }else{
                        param.franchiseId = this.addForm.franchiseId
                        param.mode = this.addForm.type
                    }

                    this.$axios.post('/Enterprise/Create', [param]).then((res) => {
                        this.$message.success("新增客户组成功");
                        this.dialogVisible = false
                        this.getList()
                        if (res.length > 0) {
                            this.$confirm(`以下部门导入失败：${res}`, '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {

                            })
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        getList(typeId = null, renew = false) {
            if (renew == true) {
                this.page = 1
            }
            this.tableData = []
            this.loading = true
            this.typeId = typeId

            let param = {
                "PageIndex": this.page,
                "PageSize": this.pageSize,
                "Key": this.namekey,
                timeType: this.timeType, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
                startDate: this.startDate, //开始时间
                endDate: this.endDate, //结束时间
                // "type": this.usertype, //1是散客，2是客户组
                "order": [
                    {
                        "column": "regdate",
                        "isDesc": true
                    }
                ],
                "type": this.typeId,
                "parentId": this.parentId,
                "cityId": this.cityId,
                "franchiseId": this.franchiseId || this.listFranchiseId || 0,
            }

            this.$axios.post('/Enterprise/List', param).then((res) => {
                this.loading = false
                this.tableData = res.rows;
                this.total = res.total;
            }).catch((err) => {
                this.loading = false
            })
        },
        views(event, row) {
            if (event.ctrlKey) {
                console.log('Ctrl + 左键点击');
                // 这里可以执行你需要的操作
                let param = []
                for (let k in this.param) {
                    if (this.param[k]) {
                        param.push(`${k}=${this.param[k]}`)
                    }
                }
                this.$router.push(`/Enterprise/list?${param.join('&')}`)

                window.open('/Enterprise/views?id=' + row.id, '_blank');
            } else {
                console.log('普通点击');
                this.viewShow.id = row.id
                this.viewShow.show = true
            }
        },
        rowClick(row) {
            // this.viewShow.id = row.id
            // this.viewShow.show = true
        },
        pageChange(e) { // 页码切换事件
            this.page = e;
            this.getList(this.typeId)
        },
        handleSizeChange(val) {
            this.page = 1;
            this.pageSize = val;
            this.getList(this.typeId)
        },
        goGuest(id) {
            this.$router.push('/user/invite?id=' + id + '&type=2')
        },
        goRecord(id) {
            this.$router.push('/user/commission?id=' + id + '&type=2')
        },
        // 选择时间
        changeTime(e) {
            console.log(e)
            this.startDate = e['startDate']
            this.endDate = e['endDate']
            this.timeType = e['timeType']
            this.getList(this.typeId)
        },
        SelectCityList(v) { //筛选客户组地区
            this.cityId = v
            this.getList(this.typeId)
        },
        // 选择加盟商
        selectFranchise(value){
            this.listFranchiseId = value,
            this.getList(true)
        },
    }
}
</script>

<style lang="scss" scoped></style>